package com.ddsso.auth.web.repository.impl;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.ddsso.auth.web.exception.DistributedSessionException;
import com.ddsso.auth.web.repository.IDistributedSessionDao;
import com.ddsso.auth.web.session.DistributedSession;

/**
 * @author zdd
 * @package com.ddsso.auth.web.repository.impl
 * @Time Created by zdd on 2016/11/2.
 * @description To-do
 */
@Component("distributedSessionDao")
public class DistributedSessionDaoImpl extends BaseDaoImpl<DistributedSession> implements IDistributedSessionDao {

    private Logger logger = Logger.getLogger(DistributedSessionDaoImpl.class);

    protected String sessionKeyPrefix = "sessionid.";


    @Override
    public DistributedSession getSession(String sessionId) {
        try {
            return this.fetch(sessionKeyPrefix + sessionId, DistributedSession.class);
        } catch (Exception e) {
            throw new DistributedSessionException("fail to get distributed session from nkv!", e);
        }
    }

    @Override
    public void createSession(DistributedSession distributedSession) {
        try {
            logger.info("创建过程，存储于redis中对应session的id："+sessionKeyPrefix + distributedSession.getId());
            this.set(sessionKeyPrefix + distributedSession.getId(), distributedSession, (long)distributedSession.getMaxInactiveInterval());
        } catch (Exception e) {
            throw new DistributedSessionException("fail to store new distributed session to nkv!", e);
        }
    }

    @Override
    public void updateSession(DistributedSession distributedSession) {
        try {
            logger.info("更新过程，存储于redis中对应session的id："+sessionKeyPrefix + distributedSession.getId());
            this.set(sessionKeyPrefix + distributedSession.getId(), distributedSession,
                    (long) distributedSession.getMaxInactiveInterval());
        } catch (Exception e) {
            throw new DistributedSessionException("fail to update distributed session to nkv!", e);
        }
    }

    @Override
    public void removeSession(DistributedSession distributedSession) {
        try {
            this.remove(sessionKeyPrefix + distributedSession.getId());
        } catch (Exception e) {
            throw new DistributedSessionException("fail to remove distributed session from nkv!", e);
        }
    }
}
